<template>
  <!-- 弹层组件 -->
  <el-dialog
    :title="`${showText}权限点`"
    :visible="showDialog"
    @close="close"
  >
    <!-- 表单 -->
    <el-form ref="formRef" :model="formData" :rules="rules" width="120px">
      <el-form-item prop="name" label="权限名称">
        <el-input v-model="formData.name" style="width:90%" />
      </el-form-item>
      <el-form-item prop="code" label="权限标识">
        <el-input v-model="formData.code" style="width:90%" />
      </el-form-item>
      <el-form-item prop="description" label="权限描述" style="margin-left:10px">
        <el-input v-model="formData.description" style="width:90%" />
      </el-form-item>
      <el-form-item label="开启" style="margin-left:10px">
        <el-switch
          v-model="formData.enVisible"
          active-value="1"
          inactive-value="0"
        />
      </el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
        <el-button size="small" @click="close">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>
import { updatePermission, addPermission } from '@/api/permission'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    pid: {
      type: Number,
      default: null
    },
    type: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      formData: {
        name: '',
        code: '',
        description: '',
        // type: '',
        enVisible: '0'
        // pid: ''// 因为做的是树 需要知道添加到哪个节点下了
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    showText() {
      return this.formData.id ? '编辑' : '新增'
    }
  },
  methods: {
    // 关闭
    close() {
      // 手动清空
      this.formData = {
        name: '',
        code: '',
        description: '',
        enVisible: '0'
      }
      this.$refs.formRef.resetFields()
      // 父组件加了 .sync 会监听 update:showDialog 事件
      this.$emit('update:showDialog', false)
    },
    btnOK() {
      this.$refs.formRef.validate(async(valid) => {
        if (valid) {
          if (this.formData.id) {
            // 有 id 是编辑
            // console.log(this.formData)
            await updatePermission(this.formData)
            this.$message.success('编辑成功')
          } else {
            // 没有 id 是添加
            await addPermission({ ...this.formData, pid: this.pid, type: this.type })
            this.$message.success('添加成功')
          }
          this.$emit('success')
          this.close()
        }
      })
    }
  }
}
</script>
